package com.muyu.payment.config;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Component
public class AlipayProperties {

    private static final String APP_ID = "appId";
    private static final String PRIVATE_KEY = "privateKey";
    private static final String PUBLIC_KEY = "publicKey";
    private static final String NOTIFY_URL = "notifyUrl";
    private static final String RETURN_URL = "returnUrl";
    private static final String SIGN_TYPE = "signType";
    private static final String CHARSET = "charset";
    private static final String GATEWAY_URL = "gatewayUrl";
    private static final String LOG_PATH = "logPath";

    private static final Map<String, String> propertiesMap = new HashMap<>();

    @PostConstruct
    public void loadProperties() {
        Resource resource = new ClassPathResource("config/alipay.properties");

        if (!resource.exists()) {
            throw new IllegalStateException(
                    "支付宝配置文件未找到！请检查文件是否存在于：src/main/resources/config/alipay.properties"
            );
        }

        try (InputStream is = resource.getInputStream()) {
            Properties props = new Properties();
            props.load(is);

            for (String key : props.stringPropertyNames()) {
                propertiesMap.put(key, props.getProperty(key));
            }

            System.out.println("支付宝配置加载成功，共加载 " + propertiesMap.size() + " 个参数。");

        } catch (IOException e) {
            throw new IllegalStateException("加载支付宝配置文件失败: " + e.getMessage(), e);
        } catch (Exception e) {
            throw new IllegalStateException("加载支付宝配置时发生未知错误", e);
        }
    }

    // 提供 getter 方法（建议改为 public）
    public String getAppId() {
        return propertiesMap.get(APP_ID);
    }

    public String getPrivateKey() {
        return propertiesMap.get(PRIVATE_KEY);
    }

    public String getPublicKey() {
        return propertiesMap.get(PUBLIC_KEY);
    }

    public String getNotifyUrl() {
        return propertiesMap.get(NOTIFY_URL);
    }

    public String getReturnUrl() {
        return propertiesMap.get(RETURN_URL);
    }

    public String getSignType() {
        return propertiesMap.get(SIGN_TYPE);
    }

    public String getCharset() {
        return propertiesMap.get(CHARSET);
    }

    public String getGatewayUrl() {
        return propertiesMap.get(GATEWAY_URL);
    }

    public String getLogPath() {
        return propertiesMap.get(LOG_PATH);
    }

    public Map<String, String> getAllProperties() {
        return new HashMap<>(propertiesMap);
    }
}